package com.jjwxc.jwjskandriod.widget;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.jjwxc.jwjskandriod.R;
import com.jjwxc.jwjskandriod.adapter.CategoryViewHolder;
import com.jjwxc.jwjskandriod.config.Url;
import com.jjwxc.jwjskandriod.framework.base.FFApplication;
import com.jjwxc.jwjskandriod.framework.http.FFNetWork;
import com.jjwxc.jwjskandriod.framework.http.FFNetWorkCallBack;
import com.jjwxc.jwjskandriod.framework.refresh.recyclerview.BaseRecyclerAdapter;
import com.jjwxc.jwjskandriod.framework.utils.PreUtils;
import com.jjwxc.jwjskandriod.framework.utils.StUtils;
import com.jjwxc.jwjskandriod.model.SubscribeRequest;
import com.jjwxc.jwjskandriod.readActivity.ReadPresenter;
import com.jjwxc.jwjskandriod.readActivity.bean.JListChapterBean;
import com.jjwxc.jwjskandriod.readActivity.utils.BookManager;
import com.jjwxc.jwjskandriod.readActivity.utils.FileUtils;
import com.jjwxc.jwjskandriod.readActivity.view.TxtChapter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class DetailsCategoryPop {
    List<TxtChapter> list = new ArrayList<>();
    PopupWindow mPopWindow;
    DetailsCategoryAdapter categoryAdapter;
    TextView tv_categorynum;

    @SuppressLint("SetTextI18n")
    public void categoryPopWindow(View mView, Activity context, String bookId, boolean monthSubscribe, DetailsCategoryItemListener itemListener) {
        View view = LayoutInflater.from(context).inflate(R.layout.details_category_pop, null, false);
        RecyclerView rv_category = view.findViewById(R.id.rv_category);
        tv_categorynum = view.findViewById(R.id.tv_categorynum);
        View views = view.findViewById(R.id.view);
        ImageView tv_quxiao = view.findViewById(R.id.tv_quxiao);
        TextView tv_cat = view.findViewById(R.id.tv_cat);
        ImageView img_cat = view.findViewById(R.id.img_cat);
        LinearLayout ll_sort = view.findViewById(R.id.ll_sort);
        LinearLayout ll_piliang = view.findViewById(R.id.ll_piliang);


        //1.构造一个PopupWindow，参数依次是加载的 View，宽高
        final PopupWindow popWindow = new PopupWindow(view,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        //设置加载动画
        popWindow.setAnimationStyle(R.style.PopupWindow);
        //这些为了点击非PopupWindow区域，PopupWindow会消失的，如果没有下面的
        //代码的话，你会发现，当你把PopupWindow显示出来了，无论你按多少次后退键
        //PopupWindow并不会关闭，而且退不出程序，加上下述代码可以解决这个问题
        popWindow.setTouchable(true);
        popWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setBackgroundAlpha(1, context);
            }
        });
        popWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));    //要为popWindow设置一个背景才有效
        //设置 popupWindow 显示的位置，参数依次是参照 View，x轴的偏移量，y轴的偏移量
        popWindow.showAtLocation(mView, Gravity.BOTTOM, 0, 0);

        mPopWindow = popWindow;
        setBackgroundAlpha(0.3f, context);
        //请求目录数据
        getListChapter(bookId, monthSubscribe);
        rv_category.setNestedScrollingEnabled(false);
        rv_category.setFocusable(false);
        rv_category.setLayoutManager(new LinearLayoutManager(context));
        rv_category.addItemDecoration(new LinearLayouDecoration(context,
                LinearLayouDecoration.HORIZONTAL, R.dimen.border8, R.color.transparent));
        rv_category.getItemAnimator().setChangeDuration(0);// 通过设置动画执行时间为0来解决闪烁问题

        categoryAdapter = new DetailsCategoryAdapter(context, itemListener);
        rv_category.setAdapter(categoryAdapter);


        tv_quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        views.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        ll_sort.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (tv_cat.getText().equals("倒序")) {
                    tv_cat.setText("正序");
                    img_cat.setImageResource(R.mipmap.zhengxu_icon);
                } else {
                    tv_cat.setText("倒序");
                    img_cat.setImageResource(R.mipmap.daoxu_icon);
                }
                Collections.reverse(list);
                categoryAdapter.setData(list);
                categoryAdapter.notifyDataSetChanged();
            }
        });


        ll_piliang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (PreUtils.getBoolean("tourist", false)) {
                    FFApplication.showToast("游客模式下无法查看");
                    return;
                }
                new DetailsDownMorePop().downMorePopWindow(mView, context, list, 0, new DetailsDownMorePop.DownMoreListener() {
                    @Override
                    public void onItemClick(int pos) {
                        if (pos == 0) {
                            categoryAdapter.notifyDataSetChanged();
                        } else if (pos == 1) {
//                            new ReadActivity().refreshBookCategory(true);
                        }
                    }
                });
            }
        });
    }


    public void getListChapter(String bookId, boolean monthSubscribe) {
        new FFNetWork().post(Url.listChapter, null, new FFNetWorkCallBack<JListChapterBean>() {
            @Override
            public void onSuccess(JListChapterBean response) {
                if (response.getCode() == 200) {
                    List<JListChapterBean.DataBean> data = response.getData();
                    list.clear();
                    for (int i = 0; i < data.size(); i++) {
                        TxtChapter txtChapter = new TxtChapter();
                        txtChapter.setBookId(bookId);
                        txtChapter.setTitle(data.get(i).getChapterName());
                        txtChapter.setChapterId(data.get(i).getChapterId());
                        txtChapter.setVip(data.get(i).isIsVip());
                        txtChapter.setHasAuth(data.get(i).isHasAuth());
                        txtChapter.setMonthSubscribe(monthSubscribe);
                        txtChapter.setPrice(data.get(i).getUserPrice() + "");
                        txtChapter.setJuan(data.get(i).getJuan());
                        list.add(txtChapter);
                    }
                    categoryAdapter.setData(list);
                    tv_categorynum.setText("完结 共" + list.size() + "章");
                }

            }

            @Override
            public boolean onFail(JListChapterBean response) {
                return false;
            }
        }, JListChapterBean.class, "{\"bookId\":\"" + bookId + "\"}");
    }

    public class DetailsCategoryAdapter extends BaseRecyclerAdapter<CategoryViewHolder> {
        private Context context;
        DetailsCategoryItemListener itemListener;

        private List<TxtChapter> mData = new ArrayList<>();


        public DetailsCategoryAdapter(Context cnt, DetailsCategoryItemListener itemListener) {
            this.context = cnt;
            this.itemListener = itemListener;

        }

        public void addData(List<TxtChapter> data) {
            if (data != null) {
                mData.addAll(data);
                notifyDataSetChanged();
            }
        }

        public void setData(List<TxtChapter> data) {
            this.mData.clear();
            addData(data);
        }

        /**
         * 创建ViewHolder
         */
        @Override
        public CategoryViewHolder onCreateViewHolder(ViewGroup parent, int viewType, boolean isItem) {

            View mView = LayoutInflater.from(context).inflate(R.layout.category_item, parent, false);
            CategoryViewHolder viewHolder_text = new CategoryViewHolder(mView);
            viewHolder_text.setIsRecyclable(false);
            return viewHolder_text;

        }

        @Override
        public CategoryViewHolder getViewHolder(View view) {
            return new CategoryViewHolder(view);
        }


        /**
         * 绑定数据：可以直接拿到已经绑定控件的Viewholder对象
         */
        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(final CategoryViewHolder holder, @SuppressLint("RecyclerView") final int position, boolean isItem) {

            holder.img_down.setVisibility(View.VISIBLE);
            if (mData.get(position).getBookId() != null
                    && BookManager
                    .isChapterCached(mData.get(position).getBookId(), mData.get(position).getChapterId())) {
                holder.img_down.setVisibility(View.GONE);
                holder.tv_name.setTextColor(Color.parseColor("#222222"));
                holder.tv_info.setTextColor(Color.parseColor("#222222"));
            } else {
                holder.img_down.setVisibility(View.VISIBLE);
                holder.img_down.setImageResource(R.mipmap.down_icon);
                holder.tv_name.setTextColor(Color.parseColor("#D2D2D2"));
                holder.tv_info.setTextColor(Color.parseColor("#D2D2D2"));
            }

            if (mData.get(position).isVip()) {
                holder.img_down.setVisibility(View.VISIBLE);
                holder.img_down.setImageResource(R.mipmap.vip_chart);
            }
            if (mData.get(position).isVip() && mData.get(position).isHasAuth()) {
                holder.img_down.setVisibility(View.VISIBLE);
                holder.img_down.setImageResource(R.mipmap.xuanzhong_icon);
            }
            if (position == 0) {
                holder.tv_name.setTextColor(Color.parseColor("#4D998D"));
            }

            if (StUtils.isEmpty(mData.get(position).getJuan())) {
                holder.img_line.setVisibility(View.GONE);
                holder.tv_info.setVisibility(View.GONE);
                holder.tv_name.setText(mData.get(position).getTitle());
            } else {
                holder.img_line.setVisibility(View.VISIBLE);
                holder.tv_info.setVisibility(View.VISIBLE);
                holder.tv_name.setText(mData.get(position).getJuan());
                holder.tv_info.setText(mData.get(position).getTitle());
            }
            holder.img_down.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    if (!mData.get(position).isHasAuth() && mData.get(position).isVip()) {
//                        if(PreUtils.getBoolean("tourist", false)){
//                            FFApplication.showToast("游客模式下无法查看");
//                            return;
//                        }
//                        List<String> list = new ArrayList<>();
//                        list.add(mData.get(position).getChapterId());
//                        buySubscribe(mData.get(position).getBookId(), list, position, mData);
//                    } else
                    if (!mData.get(position).isHasAuth() && mData.get(position).isVip()) {
                        itemListener.onItemClick(position, 0);
                        if (mPopWindow != null) {
                            mPopWindow.dismiss();
                        }
                    } else if (mData.get(position).isHasAuth() && !mData.get(position).isVip()) {
                        List<TxtChapter> slist = new ArrayList<>();
                        slist.add(mData.get(position));
                        //下载
                        new ReadPresenter().loadChapter(mData.get(position).getBookId(), slist);
                        FFApplication.showToast("成功下载" + slist.size() + "章节");
                        holder.img_down.setVisibility(View.GONE);
                        holder.tv_name.setTextColor(Color.parseColor("#222222"));
                        holder.tv_info.setTextColor(Color.parseColor("#222222"));
                    }
                }
            });
            holder.ll_item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    itemListener.onItemClick(position, 0);
                    if (mPopWindow != null) {
                        mPopWindow.dismiss();
                    }
                }
            });

        }

        @Override
        public int getAdapterItemViewType(int position) {
            return position;
        }


        @Override
        public int getAdapterItemCount() {
            return mData.size();
        }


    }

    public void buySubscribe(String mBookId, List<String> ids, int pos, List<TxtChapter> mList) {
        SubscribeRequest request = new SubscribeRequest();
        request.setBookId(mBookId);
        request.setSubscribeType("single");
        request.setChapterIds(ids);
        new FFNetWork().post(Url.subscribe, null, new FFNetWorkCallBack<String>() {
            @SuppressLint("CheckResult")
            @Override
            public void onSuccess(String response) {
                if (response.contains("200")) {
                    mList.get(pos).setHasAuth(true);
                    for (String id : ids) {
                        //删除未购买已经缓存的空章节
                        FileUtils.chapterCachedDelete(mBookId, id);
                    }
                    categoryAdapter.notifyDataSetChanged();
                    FFApplication.showToast("章节购买成功");
                }

            }

            @Override
            public boolean onFail(String response) {
                return false;
            }
        }, String.class, JSON.toJSONString(request));
    }


    public interface DetailsCategoryItemListener {
        void onItemClick(int chapter, int page);
    }

    public void setBackgroundAlpha(float alpha, Activity activity) {
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = alpha;
        activity.getWindow().setAttributes(lp);
    }
}
